<template>
	<div>
		<el-form :model="formData" label-width="110px" :rules="rules" ref="payrollformRef">
			<!-- 			<el-row>
				<el-col :span="6">
					<el-form-item label="数据年份">
						<el-date-picker type="year" v-model="formData.SettlementNumber" :disabled="!formData.PayrollType==0"></el-date-picker>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="是否扎帐">
						<el-radio-group v-model="formData.Settlement" :disabled="!formData.PayrollType==0">
							<el-radio :label="true">是</el-radio>
							<el-radio :label="false">否</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-col>
			</el-row> -->
			<!-- 			<el-row>
				<el-col :span="6">
					<el-form-item label="年度开账">
						<el-radio-group v-model="formData.Settlement" @input="radioEvent">
							<el-radio :label="true">是</el-radio>
							<el-radio :label="false">否</el-radio>
						</el-radio-group> 
					</el-form-item>
				</el-col>				
				<el-col :span="6"  v-show="formData.Settlement">
					<el-form-item label="数据年份">
						<el-date-picker type="year" v-model="formData.SettlementNumber" value-format="yyyy" @change="SettlementNumberEvent"></el-date-picker>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row v-if="CheckSettlementResult.StatusCode==500 && CheckSettlementResult.Message!=''">
				<el-col :span="24">
					<el-form-item label="提示:">
						<p style="color: #E6A23C;margin: 0px 0px;">{{ CheckSettlementResult.Message }}</p> 
					</el-form-item>
				</el-col>
			</el-row> -->
			<el-form-item label="项目名称">
				<el-input v-model="project.ProjectName" disabled></el-input>
			</el-form-item>
			<el-row>
				<el-col :span="6">
					<el-form-item label="施工类别" prop="ConstructionType">
						<el-select v-model="formData.ConstructionType" style="width: 100%;"
							:disabled="!formData.PayrollType==0">
							<el-option :value="0" label="请选择"></el-option>
							<el-option v-for="(item,index) in $parent.$parent.constructionType" :value="item.Value"
								:label="item.Description"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<!-- 				<el-col :span="6">
					<el-form-item label="施工部位" prop="ConstructionPart">
						<el-select v-model="formData.ConstructionPart" style="width: 100%;" :disabled="!formData.PayrollType==0">
							<el-option :value="0" label="请选择"></el-option>
							<el-option v-for="(item,index) in $parent.$parent.constructionPart" :value="item.Value"
								:label="item.Description"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="工作内容" prop="JobContent">
						<el-select v-model="formData.JobContent" style="width: 100%;" :disabled="!formData.PayrollType==0">
							<el-option :value="0" label="请选择"></el-option>
							<el-option v-for="(item,index) in $parent.$parent.payrollFormConstructionType"
								:value="item.Value" :label="item.Description"></el-option>
						</el-select>
					</el-form-item>
				</el-col> -->
				<el-col :span="6">
					<el-form-item label="责任人" prop="PersonId">
						<el-select v-model="formData.PersonId" style="width: 100%;"
							:disabled="!formData.PayrollType==0">
							<el-option :value="0" label="请选择"></el-option>
							<el-option v-for="(item,index) in $store.state.AllUsers" :value="item.Id"
								:label="item.UserName" v-if="item.RoleId != '1'"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="开始时间" prop="CreateTime">
						<el-date-picker style="width: 100%;" :disabled="!formData.PayrollType==0"
							v-model="formData.CreateTime" type="month" value-format="yyyy-MM-ddTHH:mm:ss.000Z"
							placeholder="请选择开始时间">
						</el-date-picker>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="单号" prop="PayrollNumber">
						<el-input v-model="formData.PayrollNumber" :disabled="!formData.PayrollType==0"></el-input>
					</el-form-item>
				</el-col>
			</el-row>

			<el-row>
				<el-col :span="6">
					<el-form-item label="方量(平方数量)" prop="Squarequantity">
						<el-input v-model="formData.Squarequantity" @blur="gettotalPrice()" type="number"
							:disabled="!formData.PayrollType==0"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="单价" prop="Price">
						<el-input v-model="formData.Price" @blur="gettotalPrice()" type="number"
							:disabled="!formData.PayrollType==0"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="总价">
						<el-input disabled v-model="formData.Totalprice"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="明细总计">
						<el-input disabled v-model="detailTotalprice" disabled></el-input>
					</el-form-item>
				</el-col>
			</el-row>

			<!-- 			<el-row>
				<el-col :span="3">
					<el-form-item label="资料文件上传">
						<UploadFileF ref="AnotherData" :multiple="true" :another-data="AnotherData"
							:showfilelist="true" :upshow="false" content="上传文件" btnsize="medium"></UploadFileF>
					</el-form-item>
				</el-col>
			</el-row> -->

			<el-row>
				<el-col :span="24">
					<el-form-item label="施工部位" prop="ConstructionPart">
						<el-input v-model="formData.ConstructionPart" :disabled="!formData.PayrollType==0"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="工作内容" prop="JobContent">
						<el-input v-model="formData.JobContent" :disabled="!formData.PayrollType==0"></el-input>
					</el-form-item>
				</el-col>
			</el-row>

			<el-row>
				<el-col :span="24">
					<el-popover placement="right" width="430" trigger="click">
						<el-table :data="projectUserList" @select="selectionLineChangeHandle" ref="projectUserLisRef"
							style="max-height: 600px;overflow: auto;">
							<el-table-column type="selection" width="42" align="center"
								:selectable="selectableEvent"></el-table-column>
							<el-table-column width="100" prop="UserName" label="姓名" align="center"></el-table-column>
							<el-table-column header-align="center" prop="UserNumber" label="工号"
								align="center"></el-table-column>
							<el-table-column header-align="center" prop="Phone" label="联系电话" align="center"
								width="150"></el-table-column>
						</el-table>
						<el-button type="primary" icon="el-icon-plus" slot="reference" size="mini"
							:disabled="!formData.PayrollType==0">添加人员</el-button>
					</el-popover>
					<el-popover v-model="approvevisible" trigger="click" placement="top" :width="180"
						style="margin-left: 10px;">
						<p>你确定要审批你的选择吗?</p>
						<div style="display: flex;justify-content: flex-end;">
							<el-button size="small" text @click="approvevisible = false">取消</el-button>
							<el-button size="small" type="primary" @click="approveuserHandler()">确定</el-button>
						</div>
						<el-button type="primary" icon="el-icon-s-check" slot="reference" size="mini"
							@click="approvevisible = true" v-show="$store.state.user.roleid == 1"
							:disabled="!formData.PayrollType==0">审批</el-button>
					</el-popover>
					<el-table :data="userList" style="width: 100%;" ref="multipleTable" @select="approveSelecthandler"
						@select-all="approveSelecthandler">
						<el-table-column type="selection" width="42" align="center"
							:selectable="selectableDetailsEvent"></el-table-column>
						<el-table-column header-align="center" fixed prop="Id" label="姓名" align="center">
							<template slot-scope="scope">
								{{ getUserInfo(scope.row,'UserName') }}
							</template>
						</el-table-column>
						<el-table-column header-align="center" prop="UserNumber" label="工号" align="center"
							width="120px">
							<template slot-scope="scope">
								{{ getUserInfo(scope.row,'UserNumber') }}
							</template>
						</el-table-column>
						<!-- 						<el-table-column header-align="center" prop="jobCreateTime" label="工作开始时间" align="center">
							<template slot-scope="scope">
								<el-date-picker v-if="scope.row.PayrollType == 0" @blur="TimeChange(scope.row)"
									v-model="scope.row.JobCreateTime" format="yyyy - MM - dd" type="date"
									placeholder="选择日期">
								</el-date-picker>
								<p v-else>{{ timeForMat(scope.row.JobCreateTime) }}</p>
							</template>
						</el-table-column>
						<el-table-column header-align="center" prop="jobCreateTime" label="工作结束时间" align="center">
							<template slot-scope="scope">
								<el-date-picker v-if="scope.row.PayrollType == 0" @blur="TimeChange(scope.row)"
									v-model="scope.row.JobEndTime" format="yyyy - MM - dd" type="date"
									placeholder="选择日期">
								</el-date-picker>
								<p v-else>{{ timeForMat(scope.row.JobEndTime) }}</p>
							</template>
						</el-table-column>
						<el-table-column header-align="center" prop="JobContent" label="工作内容" align="center">
							<template slot-scope="scope">
								<el-input v-model="scope.row.JobContent" v-if="scope.row.PayrollType == 0"></el-input>
								<p v-else>{{ scope.row.JobContent }}</p>
							</template>
						</el-table-column> -->
						<el-table-column header-align="center" prop="workingDays" label="工天" align="center">
							<template slot-scope="scope">
								<el-input v-model.number="scope.row.WorkingDays"
									v-if="scope.row.PayrollType == 0"></el-input>
								<p v-else>{{ scope.row.WorkingDays }}</p>
								<!-- <p>{{ scope.row.WorkingDays }}</p> -->
							</template>
						</el-table-column>
						<el-table-column header-align="center" prop="price" label="单价" align="center">
							<template slot-scope="scope">
								<el-input v-model.number="scope.row.Price" v-if="scope.row.PayrollType == 0"></el-input>
								<p v-else>{{ scope.row.Price }}</p>
							</template>
						</el-table-column>
						<el-table-column header-align="center" prop="price" label="金额" align="center">
							<template slot-scope="scope">
								<p>{{ (scope.row.Price * scope.row.WorkingDays).toFixed(2) }}</p>
							</template>
						</el-table-column>
						<el-table-column header-align="center" prop="price" label="备注" align="center">
							<template slot-scope="scope">
								<el-input type="textarea" v-if="scope.row.PayrollType == 0" autosize
									v-model="scope.row.Remarks"></el-input>
								<p v-else>{{ scope.row.Remarks }}</p>
							</template>
						</el-table-column>
						<el-table-column header-align="center" prop="price" label="审批状态" align="center">
							<template slot-scope="scope">
								<p v-if="scope.row.PayrollType == 0" style="color: #E6A23C;">待审批</p>
								<p v-else style="color: #67C23A;">审批完成</p>
							</template>
						</el-table-column>
						<el-table-column header-align="center" prop="UserNumber" align="center" label="操作">
							<template slot-scope="scope">
								<!-- <el-button type="text" plain size="mini" @click="tableHandler(scope.row,'updata')">{{ scope.row.Isupdata?'完成':'编辑' }}</el-button> -->
								<el-button type="text" plain size="mini" style="color: #F56C6C;"
									:disabled="!scope.row.PayrollType == 0"
									@click="tableHandler(scope.row,'delete')">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-col>
			</el-row>

			<el-row>
				<el-col :span="24" align="right">
					<el-button type="primary" @click="savePayrollFormHandler()"
						:disabled="!formData.PayrollType==0" v-loading="btn_loading">保存</el-button>
				</el-col>
			</el-row>
		</el-form>
	</div>
</template>

<script>
	import dayjs from 'dayjs'
	import UploadFileF from "../../UploadFileF";
	import {
		CheckAmount
	} from "../../../../public/Scriput/Public.js"

	export default {
		name: 'payrollForm',
		components: {
			UploadFileF
		},
		props: {
			payrollEntity: {
				type: Object,
				required: true,
			},
			closeFun: {
				type: Function,
				required: true
			},
			project: {
				type: Object,
				required: false
			},
			jobContentList: {
				type: Array,
				required: false
			}
		},
		data() {
			var squarequantityRule = (rule, value, callback) => {
				if (value == '') callback(new Error('请输入方量(平方数量)'))
				else if (!CheckAmount(value)) callback(new Error('请填写有效的方量数额(保留两位小数)'))
				else callback()
			};
			var priceRule = (rule, value, callback) => {
				if (value == '') callback(new Error('请输入方量单价'))
				else if (!CheckAmount(value)) callback(new Error('请填写有效的方量单价(保留两位小数)'))
				else callback()
			};
			return {
				formData: {},
				projectUserList: [],
				selectEdUserList: [],
				userList: [],
				approvevisible: false,
				AnotherData: {
					//项目模块
					FileType: 256,
					//项目Id号
					id: 0,
					//Type：1：收方工资单 2、应发工资单、3报销单 
					Type: 1,
					Single: false,
				},
				rules: {
					ConstructionType: [{
						trigger: 'change',
						message: '请选择施工类别',
						required: true
					}],
					// ConstructionPart:[ { trigger:'change',message:'请选择施工部位',required:true } ],
					// JobContent:[ { trigger:'change',message:'请选择工作内容',required:true } ],
					PersonId: [{
						trigger: 'change',
						message: '请选择责任人',
						required: true
					}],
					Squarequantity: [{
						trigger: 'blur',
						validator: squarequantityRule
					}],
					Price: [{
						trigger: 'blur',
						validator: priceRule
					}],
					CreateTime: [{
						trigger: 'change',
						message: '请选择开始时间',
						required: true
					}],
					PayrollNumber: [{
						trigger: 'blur',
						message: '请输入单号',
						required: true
					}],
				},
				CheckSettlementResult: {
					Status: false,
					Message: '',
					StatusCode: 200,
				},
				//数据提交中
				btn_loading:false,
			}
		},
		computed: {
			gettotalPrice() {
				const {
					Squarequantity,
					Price
				} = this.formData || 0
				let result = Squarequantity * Price
				if (isNaN(result)) {
					this.formData.Totalprice = 0
				} else {
					this.formData.Totalprice = result.toFixed(2)
				}
			},
			detailTotalprice() {
				let money_result = 0
				this.userList.map(x => {
					const {
						Price,
						WorkingDays
					} = x || 0
					money_result += (Price * WorkingDays)
				})
				return money_result.toFixed(2)
			}
		},
		watch: {
			payrollEntity: {
				handler(newvalue) {
					this.getPayrollUserAsync(this.payrollEntity.Id)
					this.$refs.projectUserLisRef.clearSelection()
					this.$refs.multipleTable.clearSelection()
				}
			}
		},
		mounted() {
			this.getPayrollUserAsync(this.payrollEntity.Id)
		},
		methods: {
			//时间转化
			timeForMat(time) {
				if (time != '') return dayjs(time).format('YYYY-MM-DD')
				else return ''
			},
			savePayrollFormHandler() {
				this.$refs.payrollformRef.validate((valid) => {
					if (valid) {
						this.btn_loading = true
						this.$http.post('PayrollForm/UpPayrollForm', {
							payroll: {
								...this.formData
							},
							users: this.userList,
							SettlementNumber: this.formData.SettlementNumber,
							Settlement: this.formData.Settlement,
						}).then(res => {
							const {
								StatusCode,
								Data
							} = res.data || 0
							this.btn_loading = false
							if (StatusCode == 200) {
								// if (this.$refs['AnotherData'].fileList.length > 0) {
								// 	this.AnotherData.id = this.formData.Id;
								// 	this.$refs['AnotherData'].submitUpload()
								// }
								this.$message.success('编辑成功')
								this.closeFun()
							} else {
								this.$message.warning('编辑失败,请重试!')
							}
						}).catch(()=>{ this.btn_loading = false })
					}
				})
			},
			//获取列表中人员
			getPayrollUserAsync(Id) {
				let _this = this
				this.$http.post('PayrollForm/GetPayrollUserAsync', {
					id: Id
				}).then(res => {
					const {
						StatusCode,
						Data
					} = res.data || 0
					if (StatusCode == 200) {
						this.userList = Data.map(x => {
							return {
								...x,
								Isupdata: true
							}
						})
						this.formData = {
							...this.payrollEntity
						}
						_this.$nextTick(() => {
							_this.$refs.multipleTable.toggleAllSelection()
						})

					}
					this.getPorjectUsers()
				})
			},
			//获取用户的信息
			getUserInfo(row, type) {
				let user = this.$store.state.AllUsers.find(u => u.Id == row.UserId) || undefined
				if (user != undefined) return user[type]
				else return ""
			},
			//表格行删除操作
			tableHandler(row, type) {
				let index = this.userList.findIndex(x => x.UserId == row.UserId)
				const {
					Id
				} = this.userList[index] || 0
				if (Id != 0) {
					// 数据库存在的数据
					this.$http.post('PayrollForm/DelPayrollFormUser', {
						id: row.Id
					}).then(res => {
						const {
							Message,
							StatusCode
						} = res.data || 0
						if (StatusCode == 200) {
							this.userList.splice(index, 1)
							this.getPayrollUserAsync(this.payrollEntity.Id)
							this.$message.success('删除成功!')
						} else {
							this.$message.success('删除失败,请重试!')
						}
					})
				} else {
					//数据库不存在的数据
					this.userList.splice(index, 1)
					this.getPayrollUserAsync(this.payrollEntity.Id)
				}
			},
			//获取项目下的人员
			getPorjectUsers() {
				this.projectUserList = []
				let {
					UserIds
				} = this.project || ''
				let ids = UserIds.split(',')
				ids.forEach(x => {
					let user = this.$store.state.AllUsers.find(u => u.Id == x) || undefined
					if (user != undefined) this.projectUserList.push({
						...user,
						isshow: true
					})
				})
				this.peopeleSelected()
			},
			//人员列表选中
			peopeleSelected() {
				this.$refs.projectUserLisRef.clearSelection()
				this.projectUserList.forEach(x => {
					let index = this.userList.findIndex(u => u.UserId == x.Id)
					if (index > -1) {
						this.$nextTick(() => {
							this.$refs.projectUserLisRef.toggleRowSelection(x)
							if (this.userList[index].PayrollType == 1) x.isshow = false
						})
					}
				})
			},
			//表格选中
			selectionLineChangeHandle(value, row) {
				const {
					Id: FormId
				} = this.payrollEntity || null
				let newvalue = [...value]
				value.forEach((x, index) => {
					const {
						Id
					} = x || 0
					let U_index = this.userList.findIndex(u => u.UserId == Id)
					if (U_index > -1) {
						newvalue[index] = this.userList[U_index]
					} else {
						newvalue[index] = {
							Id: 0,
							Delete: x.Delete,
							OperatId: 0,
							OperatDate: "",
							FormId: FormId,
							ProjectId: this.project.Id,
							JobCreateTime: '',
							JobEndTime: '',
							UserId: x.Id,
							JobContent: "",
							WorkingDays: 0,
							Price: 0,
							Remarks: "",
							PayrollType: 0,
							FormType: 2,
							Isupdata: true,
						}
					}
				})
				this.userList = [...newvalue]
			},
			//时间选择
			TimeChange(row) {
				const {
					JobCreateTime,
					JobEndTime,
					UserId
				} = row || ''
				if (JobCreateTime != '' && JobEndTime != '') {
					row.WorkingDays = (dayjs(JobEndTime).diff(JobCreateTime, 'day')) + 1
					this.$http.post('PayrollForm/UserByProjectDate', {
						userId: UserId,
						jobStartDate: JobCreateTime,
						jobEndDate: JobEndTime,
						formType: 1,
					}).then(res => {
						const {
							Message,
							Status
						} = res.data || 0
						if (!Status) {
							this.$message.warning(Message)
							row.JobCreateTime = ''
							row.JobEndTime = ''
						}
					})
				}
			},
			//审批人员列表选择
			approveSelecthandler(value, row) {
				let isover = value.filter(x => x.PayrollType == 1)
				if (isover.length > 0) {
					this.$message.warning('所选数据中存在已审批数据,请勿重复选择!')
					this.$refs.multipleTable.clearSelection()
				} else {
					this.selectEdUserList = value
				}
			},
			approveuserHandler() {
				this.approvevisible = false
				if (this.selectEdUserList.length == 0) {
					this.$message.warning('请选择你要审批的数据!')
				} else {
					this.$http.post('PayrollForm/UpPayrollTypeByAdmin', {
						users: this.selectEdUserList
					}).then(res => {
						const {
							Message,
							StatusCode
						} = res.data || 0
						if (StatusCode == 200) {
							this.getPayrollUserAsync(this.payrollEntity.Id)
							this.$message.success('审批成功!')
							this.closeFun()
						} else {
							this.$message.success('审批失败,请重试!')
						}
					})
				}
			},
			//禁选
			selectableEvent(row, index) {
				return row.isshow
			},
			//表格禁选
			selectableDetailsEvent(row, index) {
				return row.PayrollType == 1 ? false : true
			},
			//项目是否完结
			projectOver() {
				const {
					EndDate
				} = this.project || ''
				if (EndDate == undefined || EndDate == '') {
					return false
				} else {
					let chazhi = dayjs(EndDate).diff(Date(), 'day')
					return chazhi < 0 ? true : false
				}
			},
			//是否扎帐
			radioEvent(value) {
				if (!value) {
					this.formData.SettlementNumber = ''
					this.CheckSettlementResult = {
						Status: false,
						Message: '',
						StatusCode: 500,
					}
				}
			},
			//时间选择事件
			SettlementNumberEvent(value) {
				if (value == '') return
				this.$http.post('PayrollForm/CheckSettlement', {
					settlementNumber: value,
					projectId: this.project.Id
				}).then(res => {
					this.CheckSettlementResult = res.data
				})
			},
			//修改已经扎帐订单,请谨慎操作
			IsUpSettlementHandler() {
				//不存在已扎帐
				if (this.CheckSettlementResult.StatusCode == 200) {
					this.savePayrollFormHandler()
				} else {
					//存在已扎帐,修改原数据
					this.$http.post('PayrollForm/UpSettlement', {
						settlementNumber: this.formData.SettlementNumber,
						projectId: this.project.Id
					}).then(res => {
						const {
							StatusCode,
							Data,
							Message
						} = res.data || 0
						if (StatusCode == 200) {
							this.savePayrollFormHandler()
						} else {
							this.$message.warning(Message)
						}
					})
				}
			}
		}
	}
</script>

<style scoped>
	.payrollForm-header {}

	.payrollForm-main {}

	.payrollForm-bottom {
		margin-top: 5px;
		display: flex;
		justify-content: flex-end;
	}
</style>